package com.itheima.security.distributed.gateway.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableResourceServer;
import org.springframework.security.oauth2.config.annotation.web.configuration.ResourceServerConfigurerAdapter;
import org.springframework.security.oauth2.config.annotation.web.configurers.ResourceServerSecurityConfigurer;
import org.springframework.security.oauth2.provider.token.TokenStore;

/**
 * @author Administrator
 * @version 1.0
 **/
@Configuration
public class ResouceServerConfig  {

    public static final String RESOURCE_ID = "res1";


    //uaa资源服务配置
    @Configuration
    @EnableResourceServer
    public class UAAServerConfig extends ResourceServerConfigurerAdapter {
        @Autowired
        private TokenStore tokenStore;

        @Override
        public void configure(ResourceServerSecurityConfigurer resources){
            resources.tokenStore(tokenStore)//指定令牌如何访问，tokenStore这个bean就是tokenconfig中配置的token设置(存储方案,加密解密规则)
                    .resourceId(RESOURCE_ID)//资源id
                    .stateless(true);//认证服务无状态
        }

        /**
         * 访问权限控制
         *
         * 因为uaa是登录认证服务，所以放行所有请求然他们去登录认证服务进行登录认证
         *
         * @param http
         * @throws Exception
         */
        @Override
        public void configure(HttpSecurity http) throws Exception {
            http.authorizeRequests()
                 .antMatchers("/uaa/**").permitAll();//允许访问/uaa/**(全部放行)
        }
    }


    //order资源
    //uaa资源服务配置
    @Configuration
    @EnableResourceServer
    public class OrderServerConfig extends ResourceServerConfigurerAdapter {
        @Autowired
        private TokenStore tokenStore;

        /**
         * order资源服务设置
         *
         * 这里的配置与上面uaa的token配置作用一样
         *
         * @param resources
         */
        @Override
        public void configure(ResourceServerSecurityConfigurer resources){
            resources.tokenStore(tokenStore)
                    .resourceId(RESOURCE_ID)
                    .stateless(true);
        }

        /**
         * 访问权限控制
         *
         * 因为这里是请求准备去的资源服务,所以需要在网关解析出token后,拿到权限字段匹配网关是否放行去资源服务
         * 设置访问资源的Scope权限为ROLE_API
         *
         * 网关先通过 scope 做粗粒度权限筛选 → 放行后资源服务再通过 authority 做细粒度权限控制。
         *
         * @param http
         * @throws Exception
         */
        @Override
        public void configure(HttpSecurity http) throws Exception {
            http
                    .authorizeRequests()
                    .antMatchers("/order/**").access("#oauth2.hasScope('ROLE_API')");//访问/order/**需要权限ROLE_API
        }
    }


    //配置其它的资源服务..


}
